import React, { useState, useEffect } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    Typography,
    Box,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Paper,
    CircularProgress,
    Alert
} from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import DownloadIcon from '@mui/icons-material/Download';
import DeleteIcon from '@mui/icons-material/Delete';
import { getResumeList, uploadResume, deleteResume, downloadResume, ResumeInfo } from '../../../api/resume';
import { useParams } from 'react-router-dom';
import './ResumeUploadDialog.css';

interface ResumeUploadDialogProps {
    open: boolean;
    onClose: () => void;
    onUploadSuccess: () => void;
}

const ResumeUploadDialog: React.FC<ResumeUploadDialogProps> = ({ open, onClose, onUploadSuccess }) => {
    // 获取路由参数
    const { record_id, sid } = useParams<{ record_id: string; sid: string }>();

    // 简历列表
    const [resumeList, setResumeList] = useState<ResumeInfo[]>([]);

    // 加载状态
    const [loading, setLoading] = useState<boolean>(false);

    // 错误信息
    const [error, setError] = useState<string | null>(null);

    // 上传状态
    const [uploading, setUploading] = useState<boolean>(false);

    // 删除状态
    const [deleting, setDeleting] = useState<boolean>(false);

    // 获取简历列表
    const fetchResumeList = async () => {
        if (!record_id || !sid) return;

        setLoading(true);
        setError(null);

        try {
            // 获取当前登录用户ID，这里假设从localStorage中获取
            const uid = localStorage.getItem('uid') || '1';

            const response = await getResumeList({
                uid,
                sid,
                record_id
            });

            console.log('Resume list:', response);

            setResumeList(response);
        } catch (error) {
            console.error('获取简历列表失败:', error);
            setError('获取简历列表失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 对话框打开时获取简历列表
    useEffect(() => {
        if (open) {
            fetchResumeList();
        }
    }, [open]);

    // 处理文件上传
    const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
        if (!record_id || !sid) return;

        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];
        console.log('选择的文件:', file.name);

        // 验证文件类型
        // const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        // if (fileExtension !== '.xlsx') {
        //     setError('文件类型不支持，请选择Excel文件(.xlsx格式)');
        //     event.target.value = '';
        //     return;
        // }

        setUploading(true);
        setError(null);

        try {
            // 获取当前登录用户ID，这里假设从localStorage中获取
            const uid = localStorage.getItem('uid') || '1';

            await uploadResume({
                uid,
                sid,
                record_id,
                file: file
            });

            // 上传成功后重新获取简历列表
            await fetchResumeList();

            // 通知父组件上传成功
            onUploadSuccess();
        } catch (error) {
            console.error('上传简历失败:', error);
            setError('上传简历失败，请稍后重试');
        } finally {
            setUploading(false);
            // 清空文件输入框
            event.target.value = '';
        }
    };

    // 处理简历下载
    const handleDownload = (resumeId: string, resumeName: string) => {
        try {
            downloadResume(resumeId, resumeName);
        } catch (error) {
            console.error('下载简历失败:', error);
            setError('下载简历失败，请稍后重试');
        }
    };

    // 处理简历删除
    const handleDelete = async (resumeId: string) => {
        if (!record_id || !sid) return;

        setDeleting(true);
        setError(null);

        try {
            // 获取当前登录用户ID，这里假设从localStorage中获取
            const uid = localStorage.getItem('uid') || '1';

            await deleteResume({
                uid,
                sid,
                record_id,
                resume_id: resumeId
            });

            // 删除成功后重新获取简历列表
            await fetchResumeList();

            // 通知父组件上传成功（实际上是删除成功，但也需要更新父组件状态）
            onUploadSuccess();
        } catch (error) {
            console.error('删除简历失败:', error);
            setError('删除简历失败，请稍后重试');
        } finally {
            setDeleting(false);
        }
    };

    return (
        <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth className="resume-upload-dialog">
            <DialogTitle>
                <Box display="flex" justifyContent="space-between" alignItems="center">
                    <Typography variant="h6">简历管理</Typography>
                    <Box>
                        <input
                            accept=".xlsx"
                            style={{ display: 'none' }}
                            id="resume-upload-button"
                            type="file"
                            onChange={handleFileUpload}
                            disabled={uploading}
                        />
                        <label htmlFor="resume-upload-button">
                            <Button
                                variant="contained"
                                component="span"
                                // startIcon={<CloudUploadIcon />}
                                disabled={uploading}
                                className="upload-button">
                                <Box style={{ color: '#fff', display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <CloudUploadIcon />
                                    {uploading ? '上传中...' : '上传'}
                                </Box>
                            </Button>
                        </label>
                    </Box>
                </Box>
            </DialogTitle>

            <DialogContent dividers>
                {error && (
                    <Alert severity="error" sx={{ mb: 2 }}>
                        {error}
                    </Alert>
                )}

                {loading ? (
                    <Box display="flex" justifyContent="center" alignItems="center" minHeight={200}>
                        <CircularProgress />
                    </Box>
                ) : (
                    <TableContainer component={Paper} sx={{ mb: 2 }}>
                        <Table>
                            <TableHead sx={{ backgroundColor: '#f5f5f5' }}>
                                <TableRow>
                                    <TableCell sx={{ fontWeight: 'bold', width: '60%' }}>简历名称</TableCell>
                                    <TableCell sx={{ fontWeight: 'bold', width: '40%' }}>操作</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {resumeList.map((resume) => (
                                    <TableRow key={resume.resume_id} hover>
                                        <TableCell>{resume.resume_name}</TableCell>
                                        <TableCell>
                                            <Box display="flex" gap={1}>
                                                <Button
                                                    variant="outlined"
                                                    size="small"
                                                    startIcon={<DownloadIcon />}
                                                    onClick={() => handleDownload(resume.resume_id, resume.resume_name)}
                                                    sx={{ minWidth: 100 }}
                                                    className="download-button">
                                                    下载
                                                </Button>
                                                <Button
                                                    variant="outlined"
                                                    size="small"
                                                    color="error"
                                                    startIcon={<DeleteIcon />}
                                                    onClick={() => handleDelete(resume.resume_id)}
                                                    disabled={deleting}
                                                    sx={{ minWidth: 100 }}
                                                    className="delete-button">
                                                    删除
                                                </Button>
                                            </Box>
                                        </TableCell>
                                    </TableRow>
                                ))}

                                {resumeList.length === 0 && (
                                    <TableRow>
                                        <TableCell colSpan={2} align="center" sx={{ py: 3 }}>
                                            <Typography color="textSecondary">暂无简历</Typography>
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>
                )}
            </DialogContent>

            <DialogActions>
                <Button onClick={onClose} color="primary">
                    关闭
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default ResumeUploadDialog;
